/**
 * 封装常用、可复用性高的Uniapp的Api
 * 可按需引入
 */
// 轻提示
const toast = ({title = '', icon = 'none', duration = 1400, success} = {}) => {
	uni.showToast({
		title,
		icon,
		duration: duration,
		mask: true,
		success: () => success && success()
	})
}

// 模态框提示 => 包含 ‘确认’， ‘取消’
const modal = ({
	title = '提示',
	content = '',
	cancelText = '取消',
	cancelColor = '#666666',
	confirmText = '确认',
	confirmColor = '#896a33',
	callback,
	cancelBack
} = {}) => {
	uni.showModal({
		title,
		content,
		cancelText,
		cancelColor,
		confirmText,
		confirmColor,
		success: function (res) {
			if (res.confirm) {
				callback()
			} else {
				cancelBack && cancelBack()
			}
		}
	})
}

// 模态框提示 => 仅包含 ‘确认’
const comfirmModal = ({
	title = '提示',
	content = '',
	confirmText = '确认',
	confirmColor = '#896a33',
	callback
} = {}) => {
	uni.showModal({
		title,
		content,
		confirmText,
		confirmColor,
		showCancel: false,
		success: function (res) {
			if (res.confirm) {
				callback && callback()
			}
		}
	})
}

// loading
const loading = title => {
	uni.showLoading({
		mask: true,
		title,
		fail: () => {
			uni.hideLoading()
		}
	})
}

// 跳转Tab页
const switchTab = url => {
	if (!url)
		return toast({
			title: '跳转地址必填'
		})
	uni.switchTab({
		url
	})
}

// 普通页面之间跳转
// 注: 如果两个页面之间通信数据量过大，建议采用跳转成功回调的方式传值
// eg: res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'xxx' })
const pageNav = ({url, events = {}, success} = {}) => {
	if (!url)
		return toast({
			title: '跳转地址不能为空'
		})
	uni.navigateTo({
		url,
		animationType: 'slide-in-right',
		animationDuration: 200,
		events,
		success: (res) => success && success(res)
	})
}

// 页面返回
const pageBack = (backNumber = 1) => {
	const pageLength = getCurrentPages().length // eslint-disable-line
	if (pageLength > 1) {
		uni.navigateBack({
			delta: backNumber
		})
	} else {
		switchTab('/pages/index/index')
	}
}

// 关闭当前页，跳转某个页面
const redirect = url => {
	if (!url)
		return toast({
			title: '跳转地址不能为空'
		})
	uni.redirectTo({
		url
	})
}

// 获取定位
const getLocation =  () => {
	const locationPromise = new Promise((resolve, reject) => {
		uni.getLocation({
			success: res => {
				resolve(res)
			},
			fail: err => {
				reject(err)
			}
		})
	})
	// // #ifdef APP-PLUS
	// let result = await $store('huaweiAudit').checkPermission('ACCESS_COARSE_LOCATION')
	// if (!result) return Promise.reject('未获取定位')
	// return locationPromise
	// // #endif
	// #ifdef MP-WEIXIN
	return locationPromise
	// #endif
}

// 打开地图查看定位
const openLocation = ({latitude, longitude, name, address}) => {
	uni.openLocation({
		latitude,
		longitude,
		name,
		address,
		success() {
			console.log('已成功打开地图')
		}
	})
}

// 拨打电话
const makePhoneCall = async (phone = '') => {
	if (!phone) return toast({title: '无效的号码'})
	// #ifdef APP-PLUS
	// let result = await $store('huaweiAudit').checkPermission('CALL_PHONE')
	// if (!result) return
	// #endif
	uni.makePhoneCall({
		phoneNumber: phone
	})
}

// 设置剪贴板内容
const setClipboardData = (data = '') => {
	if (!data) return toast({title: '无效的内容'})
	uni.setClipboardData({
		data,
		success() {
			toast({title: '已复制'})
		},
		fail: err => {
			console.log('err:', err)
		}
	})
}

// 保存图片到系统相册
const saveImageToPhotos = (filePath = '') => {
	if (!filePath) return toast({title: '无效的图片'})
	uni.downloadFile({
		url: filePath,
		success: res => {
			uni.getSetting({
				success: result => {
					if (result.authSetting['scope.writePhotosAlbum']) {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success() {
								toast({title: '保存成功'})
							}
						})
					} else {
						toast({title: '请先授权保存图片权限', icon: 'none'})
					}
				}
			})
		},
		fail: err => {
			toast({title: '发票图片保存失败', icon: 'none'})
		}
	})
}

// 校验邮箱格式
const checkEmail = (email = '') => {
	const reg = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
	return reg.test(email)
}

export default {
	toast,
	modal,
	comfirmModal,
	loading,
	switchTab,
	pageNav,
	pageBack,
	redirect,
	getLocation,
	openLocation,
	makePhoneCall,
	setClipboardData,
	saveImageToPhotos,
	checkEmail
}
